package cn.dgut.loginManager;

import cn.dgut.Entity.User;
import cn.dgut.Utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/loginServlet")
public class lloginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        int flag=0;
        JDBCUtils utils = new JDBCUtils();
        String aa= request.getParameter("user_name");
        String bb= request.getParameter("password");

        String  sql = "select * from User";

        JDBCUtils jdbcUtils = new JDBCUtils();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        User temp =new User();
        try {
            conn = jdbcUtils.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            //5.执行sql
            rs = stmt.executeQuery(sql);
            while(rs.next()) {
                temp = new User(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6));
                if(temp.getUser_name().equals(aa)&&temp.getUser_passwd().equals(bb)){
                    flag=1;
                    break;
                }
                if(temp.getUser_name().equals(aa)&&(!temp.getUser_passwd().equals(bb))) flag=2;
            }
            //提交事务
            conn.commit();
        } catch (Exception e) {
            //事务回滚
            try {
                if(conn != null) {
                    conn.rollback();
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            jdbcUtils.close(stmt,conn);
        }

        if(flag==1){
            Map<String, String> info = new HashMap<String, String>();
            info.put("name", temp.getUser_name());
            info.put("id", String.valueOf(temp.getUser_id()));
            HttpSession session = request.getSession(true);
            session.setAttribute("isBackstageLogin", info);
            response.sendRedirect("http://localhost:8080/backstage/index.jsp");
        }
        else
            response.sendRedirect("http://localhost:8080/backstage/login.jsp");

    }

}
